#include "road_sensor.h"
#include <iostream>
using namespace std;
using namespace adevs;

// Assign locally unique identifiers to the ports
const int RoadSensor::in_arrive = 0;
const int RoadSensor::in_free = 1;
const int RoadSensor::out_depart = 2;
const int RoadSensor::out_free = 3;
const int RoadSensor::out_tick_event = 4;

RoadSensor::RoadSensor():
	Atomic<IO_Type>(), // Initialize the parent Atomic model
	resend_free(false),
	vehicle(NULL)
{
}

void RoadSensor::delta_ext(double e, const Bag<IO_Type>& xb)
{
	Bag<IO_Type>::const_iterator i = xb.begin();
	for (; i != xb.end(); i++)
	{
		if ((*i).port == in_arrive)
		{
			vehicle = new Vehicle(*((Vehicle*)(*i).value));
		}
		else 
		{
			resend_free = true;
		}
	}
}
	
void RoadSensor::delta_int()
{
	if (resend_free)
	{
		resend_free = false;
		return;
	}
	vehicle = NULL;
}

void RoadSensor::delta_conf(const Bag<IO_Type>& xb)
{
}

void RoadSensor::output_func(Bag<IO_Type>& yb)
{
	if (resend_free)
	{
		IO_Type q(out_free, new io_type()); // preposleme dalsi
		yb.insert(q);

		return;
	}

	IO_Type out(out_depart,  (io_type*)vehicle);
	yb.insert(out);

	IO_Type evnt(out_tick_event, (io_type*)new RoadSensorEvent());
	yb.insert(evnt);
}

double RoadSensor::ta()
{
	if (resend_free) return 0;
	if (vehicle != NULL) return 0;
	return DBL_MAX;
}

void RoadSensor::gc_output(Bag<IO_Type>& g)
{
	Bag<IO_Type>::iterator i;
	for (i = g.begin(); i != g.end(); i++)
	{
		delete (*i).value;
	}
}

RoadSensor::~RoadSensor()
{
}
